import optparse

from scapy.all import *


# 回调详情函数
def Pack_CallBack(packet):
    print("*" * 50)
    # 显示源IP、源端口、目的IP、目的端口
    print("[{}] Source:{}:{}----->Target:{}:{}".format(TimeStamp_To_Time(packet.time),
                                                       packet[IP].src,
                                                       packet.sport,
                                                       packet[IP].dst,
                                                       packet.dport))
    # 打印TTL值
    print("TTL:{0}".format(packet[IP].ttl))
    # 使用scapy内置函数show()打印数据包的内容
    print(packet.show())


# 时间戳转换函数
def TimeStamp_To_Time(timeStamp):
    timeTmp = time.localtime(timeStamp)
    myTime = time.strftime("%Y-%m-%d %H:%M:%S", timeTmp)
    return myTime


if __name__ == '__main__':
    parser = optparse.OptionParser()
    # 添加ip参数 -i
    parser.add_option("-i", "--IP", dest="hostIP", default='127.0.0.1', type="string",
                      help="IP address [default=127.0.0.1]")
    # 添加数据包总数参数 -c
    parser.add_option("-c", "--count", dest="packetCount", default=5, type="int", help="Packet count [default=5]")

    # 添加报错文件名参数 -o
    parser.add_option("-o", "--output", dest="fileName", default="new.pcap", type="string",
                      help="save filename [default=new.pcap]")
    (options, args) = parser.parse_args()
    print(options)
    print(args)
    defFilter = "dst " + options.hostIP
    packets = sniff(filter=defFilter, prn=Pack_CallBack, count=options.packetCount)
    print(packets)
    # 将输出文件保存
    wrpcap(options.fileName, packets)
